<template>
  <div class="system-message">
    <div class="message-container">
      <div class="message-header">
        <h2>系统通知</h2>
        <el-button type="primary" size="small" @click="markAllAsRead" :disabled="unreadMessages.length === 0">
          全部标为已读
        </el-button>
      </div>

      <!-- 消息列表 -->
      <div class="message-list" v-loading="loading">
        <el-empty v-if="!loading && !messages.length" description="暂无系统通知" />
        <template v-else>
          <div v-for="message in messages" :key="message.id" class="message-item" :class="{ unread: message.status === 'unread' }">
            <div class="message-content">
              <div class="message-title">
                <span class="dot" v-if="message.status === 'unread'"></span>
                {{ message.title }}
              </div>
              <div class="message-body">{{ message.content }}</div>
              <div class="message-footer">
                <span class="message-time">{{ message.createTime }}</span>
                <el-button 
                  v-if="message.status === 'unread'"
                  type="primary" 
                  link 
                  @click="markAsRead(message.notificationId)"
                >
                  标为已读
                </el-button>
              </div>
            </div>
          </div>
        </template>
      </div>

      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useUserStore } from '@/store/user'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const messages = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 计算未读消息
const unreadMessages = computed(() => {
  return messages.value.filter(msg => msg.status === 'unread')
})

// 获取消息列表
const fetchMessages = async () => {
  if (!userStore.token) return
  
  loading.value = true
  try {
    const response = await axios.get('/app/message/list', {
      params: {
        userId: userStore.userInfo.id,
        type: 'system',
        page: currentPage.value,
        size: pageSize.value
      }
    })
    console.log(response.data);
    if (response.data.code === 200) {
        messages.value = response.data.data.list
        total.value = response.data.data.total
        
    }
  } catch (error) {
    console.error('获取消息列表失败:', error)
    ElMessage.error('获取消息列表失败')
  } finally {
    loading.value = false
  }
}

// 标记单条消息为已读
const markAsRead = async (messageId) => {
  try {
    const response = await axios.post('/app/message/read', {
      messageId,
      userId: userStore.userInfo.id
    })
    
    if (response.data.code === 200) {
      // 立即更新本地消息状态
      const message = messages.value.find(msg => msg.notificationId === messageId)
      if (message) {
        message.status = 'read'
      }
      ElMessage.success('已标记为已读')
    }
  } catch (error) {
    console.error('标记已读失败:', error)
    ElMessage.error('标记已读失败')
  }
}

// 标记所有消息为已读
const markAllAsRead = async () => {
  if (unreadMessages.value.length === 0) return
  
  try {
    const response = await axios.post('/app/message/readall', {
      userId: userStore.userInfo.id,
      type: 'system'
    })
    
    if (response.data.code === 200) {
      // 立即更新所有消息的本地状态
      messages.value.forEach(msg => {
        msg.status = 'read'
      })
      ElMessage.success('已全部标记为已读')
    }
  } catch (error) {
    console.error('标记全部已读失败:', error)
    ElMessage.error('标记全部已读失败')
  }
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchMessages()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchMessages()
}

// 组件挂载时获取消息
onMounted(() => {
  fetchMessages()
})
</script>

<style scoped>
.system-message {
  padding: 20px;
  min-height: calc(100vh - 60px);
  background-color: #f4f5f6;
  min-height: 100vh;
  /* 添加背景图片 */
  background-image: url("/images/backgroundImages/blueArchive6.jpg"); /* 图片路径 */
  background-size: cover; /* 覆盖整个区域 */
  background-position: center; /* 居中显示 */
  background-repeat: no-repeat; /* 不重复 */
  background-attachment: fixed; /* 固定背景 */
}

.message-container {
  max-width: 800px;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.message-header h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.message-list {
  min-height: 300px;
}

.message-item {
  padding: 20px;
  border-bottom: 1px solid #eee;
  transition: background-color 0.3s;
}

.message-item:hover {
  background-color: #f9f9f9;
}

.message-item.unread {
  background-color: #f6f8ff;
}

.message-content {
  .message-title {
    font-size: 16px;
    font-weight: 500;
    color: #333;
    margin-bottom: 10px;
    display: flex;
    align-items: center;

    .dot {
      width: 6px;
      height: 6px;
      background-color: #f85959;
      border-radius: 50%;
      margin-right: 8px;
    }
  }

  .message-body {
    font-size: 14px;
    color: #666;
    line-height: 1.6;
    margin-bottom: 10px;
  }

  .message-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .message-time {
      font-size: 12px;
      color: #999;
    }
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 